package com.ruoyi.mobile.api;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageSerializable;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.AjaxResults;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.SnowFlakeUtil;
import com.ruoyi.qsng.domain.*;
import com.ruoyi.qsng.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author kl
 * @Date 2023/6/8 0008 10:04
 */
@Api(tags = "首页相关")
@RestController
@RequestMapping("/mobile/index")
public class HomeApi extends BaseController {
    @Autowired
    private IKCourseClassesService kCourseClassesService;
    @Autowired
    private IKCourseLocationService kCourseLocationService;
    @Autowired
    private IKAgeGroupService kAgeGroupService;
    @Autowired
    private IKClassCategoryService kClassCategoryService;
    @Autowired
    private IKCourseTypeService kCourseTypeService;
    @Autowired
    private IKCourseService kCourseService;
    @Autowired
    private IKCourseCollectService kCourseCollectService;
    @Autowired
    private IKUsersService kUsersService;
    @Autowired
    private IKCarouselFigureService kCarouselFigureService;
    @Autowired
    private IKNoticeService kNoticeService;
    @Autowired
    private IKImportantNewsService kImportantNewsService;
    @Autowired
    private IKCenterOverviewService kCenterOverviewService;
    @Autowired
    private IKActivityService kActivityService;

    @Autowired
    private IKActivityCollectService kActivityCollectService;

    @Autowired
    private IKActivityPurchaseService kActivityPurchaseService;

    @Autowired
    private IKCoursePurchaseService kCoursePurchaseService;

    @Autowired
    private IKIntegralOrderService kIntegralOrderService;

    @Autowired
    private IKIntegralDetailedService kIntegralDetailedService;

    @Autowired
    private IKLearningHomeService kLearningHomeService;

    @Autowired
    private IKTalentRecruitmentService kTalentRecruitmentService;

    @Autowired
    private ITStudentService tStudentService;


    /*************************************************第一屏***********************************************/


    @ApiOperation(value = "首页--查询轮播图片列表")
    @ApiImplicitParams({
    })
    @GetMapping("/carouselFigureList")
    public AjaxResult carouselFigureList(KCarouselFigure kCarouselFigure)
    {
        List<KCarouselFigure> list = kCarouselFigureService.selectKCarouselFigureList(kCarouselFigure);
        return success(list);
    }



    @ApiOperation(value = "首页--查询通知公告广播信息")
    @ApiImplicitParams({
    })
    @GetMapping("/noticeLb")
    public AjaxResult noticeLb(KNotice kNotice)
    {
        kNotice.setIsGb(1);
        List<KNotice> list = kNoticeService.selectKNoticeList(kNotice);

        return success(list);
    }


    @ApiOperation(value = "首页--查询新闻动态列表")
    @ApiImplicitParams({
    })
    @GetMapping("/importantNewsList")
    public AjaxResults importantNewsList(            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                       @RequestParam(required = false, defaultValue = "10") Integer pageSize,KImportantNews kImportantNews)
    {
        PageHelper.startPage(pageNum, pageSize);
        List<KImportantNews> list = kImportantNewsService.selectKImportantNewsList(kImportantNews);
        return AjaxResults.success(new PageSerializable<>(list));
    }



    @ApiOperation(value = "首页--查询通知公告详情")
    @ApiImplicitParams({
    })
    @GetMapping("/getNotice")
    public AjaxResults getNotice(String id)
    {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        KNotice kNotice =kNoticeService.selectKNoticeById(id);
//        this.inserKIntegralOrder(userId,kNotice.getIntegral(),"浏览通知公告");

        return AjaxResults.success(kNotice);
    }

    @ApiOperation(value = "首页--查询新闻动态详情")
    @ApiImplicitParams({
    })
    @GetMapping("/getImportantNews")
    public AjaxResults getImportantNews(String id)
    {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        KImportantNews kImportantNews=kImportantNewsService.selectKImportantNewsById(id);
//        this.inserKIntegralOrder(userId,kImportantNews.getIntegral(),"浏览中心概况");
        return AjaxResults.success(kImportantNews);
    }



    @ApiOperation(value = "首页--查询通知公告列表")
    @ApiImplicitParams({
    })
    @GetMapping("/noticeList")
    public AjaxResults noticeList(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,KNotice kNotice)
    {
        PageHelper.startPage(pageNum, pageSize);
        kNotice.setIsGb(1);
        List<KNotice> list = kNoticeService.selectKNoticeList(kNotice);
        return AjaxResults.success(new PageSerializable<>(list));
    }

    @ApiOperation(value = "首页--接口整合")
    @ApiImplicitParams({
    })
    @GetMapping("/homePage")
    public AjaxResults homePage()
    {
        KNotice kNotice =new KNotice();
        kNotice.setIsGb(1);
        List<KNotice> list = kNoticeService.selectKNoticeList(kNotice);

        KCarouselFigure kCarouselFigure = new KCarouselFigure();
        List<KCarouselFigure> list1 = kCarouselFigureService.selectKCarouselFigureList(kCarouselFigure);

        HashMap<String, Object> map =new HashMap<>();
        map.put("KNotice",list);
        map.put("KCarouselFigure",list1);
        return AjaxResults.success(map);
    }
    /*************************************************第二屏公共***********************************************/



    @ApiOperation(value = "查询年龄段列表")
    @ApiImplicitParams({
    })
    @GetMapping("/ageGroupList")
    public AjaxResult ageGroupList(KAgeGroup kAgeGroup)
    {
        List<KAgeGroup> list = kAgeGroupService.selectKAgeGroupList(kAgeGroup);
        return success(list);
    }


    @ApiOperation(value = "获取用户信息详细信息")
    @ApiImplicitParams({
    })
    @GetMapping(value = "/getUserInfo")
    public AjaxResult getUserInfo()
    {
        LoginUser loginUser=getLoginUser();
        KUsers kUsers=new KUsers();
        kUsers.setUserName(loginUser.getUser().getPhonenumber());
        List<KUsers> list = kUsersService.selectKUsersList(kUsers);
        if (StringUtils.isEmpty(list))
        {
            return success(new ArrayList<KUsers>());
        }else{
            return success(list.get(0));
        }
    }


    @ApiOperation(value = "修改用户信息及发起购买")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "必填字段---------类型 1课程 2活动",name = "type",dataType = "int",paramType = "query"),
            @ApiImplicitParam(value = "必填字段---------当条课程/活动的id",name = "activityId",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(value = "必填字段---------当类型为课程时起作用，购买节次 0全部 其余为数量",name = "purchaseSection",dataType = "Long",paramType = "query"),
    })
    @PostMapping(value = "/editUserInfo")
    @Transactional
    public AjaxResults editUserInfo(KUsers kUsers,int type,Long activityId,Long purchaseSection)
    {

        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");

        //修改信息
        kUsers.setId(String.valueOf(userId));
        int rows=kUsersService.updateKUsers(kUsers);
        if(rows==0){
            return AjaxResults.error("修改用户信息失败！");
        }else{
            switch (type){
                case 1:
                    //查询课程信息
                    KCourse kCourse=kCourseService.selectKCourseById(String.valueOf(activityId));
                    //课程对接支付--未实现
                    //增加报名记录
                    KCoursePurchase kCoursePurchase = new KCoursePurchase();
                    kCoursePurchase.setUserId(String.valueOf(userId));
                    kCoursePurchase.setCourseId(String.valueOf(activityId));
                    List<KCoursePurchase> kCoursePurchaseList=kCoursePurchaseService.selectKCoursePurchaseList(kCoursePurchase);
                    if(kCoursePurchaseList.size()>0){
                        return AjaxResults.error("您已经报名该课程！");
                    }
                    kCoursePurchase.setPurchaseSection(purchaseSection.intValue());
                    kCoursePurchase.setState(0);
                    // 全部
                    if(purchaseSection==0){
                        kCoursePurchase.setPrice(new BigDecimal(Integer.parseInt(kCourse.getSection().toString())).multiply(kCourse.getPrice()));
                        kCoursePurchase.setPurchaseSection(kCourse.getSection());
                    }else {
                        kCoursePurchase.setPrice(new BigDecimal(Integer.parseInt(purchaseSection.toString())).multiply(kCourse.getPrice()));
                        kCoursePurchase.setPurchaseSection(Integer.parseInt(purchaseSection.toString()));
                    }
                    String id=SnowFlakeUtil.getNextId();
                    kCoursePurchase.setOutTradeNo(id);
                    return kCoursePurchaseService.insertKCoursePurchaseForApp(kCoursePurchase);
                default:
                    //活动
                    KActivityPurchase kActivityPurchase = new KActivityPurchase();
                    kActivityPurchase.setActivityId(String.valueOf(activityId));
                    kActivityPurchase.setUserId(String.valueOf(userId));
                    List<KActivityPurchase>  kActivityPurchaseList=kActivityPurchaseService.selectKActivityPurchaseList(kActivityPurchase);
                    if(kActivityPurchaseList.size()>0){
                        return AjaxResults.error("您已经报名该活动！");
                    }
                    KActivity kActivity=kActivityService.selectKActivityById(String.valueOf(activityId));
                    this.inserKIntegralOrder(userId,kActivity.getIntegral(),"活动报名",3,"");
                    return kActivityPurchaseService.insertKActivityPurchaseForApp(kActivityPurchase);
            }

        }
    }

    @ApiOperation(value = "修改用户信息及发起购买---新")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "必填字段---------类型 1课程 2活动",name = "type",dataType = "int",paramType = "query"),
            @ApiImplicitParam(value = "必填字段---------当条课程/活动的id",name = "activityId",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(value = "必填字段---------当类型为课程时起作用，购买节次 0全部 其余为数量",name = "purchaseSection",dataType = "Long",paramType = "query"),
    })
    @PostMapping(value = "/editUserInfoNew")
    @Transactional
    public AjaxResults editUserInfoNew(KUsers kUsers,int type,Long activityId,Long purchaseSection)
    {

        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        //修改信息
//        kUsers.setId(String.valueOf(userId));
//        int rows=kUsersService.updateKUsers(kUsers);
//        if(rows==0){
//            return AjaxResults.error("修改用户信息失败！");
//        }else{
        //往学生信息表添加数据
        TStudent tStudent = new TStudent();
        tStudent.setIdCard(kUsers.getNickCard());
        List<TStudent> tStudentList =tStudentService.selectTStudentList(tStudent);
        if(tStudentList.size()==0){
            tStudent.setStudentName(kUsers.getNickName());
            tStudent.setAge(Long.valueOf(kUsers.getNickAge()));
            tStudent.setNation(kUsers.getNickNation());
            tStudent.setSchool(kUsers.getNickSchool());
            tStudent.setGrade(kUsers.getNickLevel());
            tStudent.setProfileUser(kUsers.getAvatarUrl());
            tStudentService.insertTStudent(tStudent);
        }
            switch (type){
                case 1:
                    //查询课程信息
                    KCourse kCourse=kCourseService.selectKCourseById(String.valueOf(activityId));
                    //课程对接支付--未实现
                    //增加报名记录
                    KCoursePurchase kCoursePurchase = new KCoursePurchase();
                    kCoursePurchase.setUserId(String.valueOf(userId));
                    kCoursePurchase.setCourseId(String.valueOf(activityId));
//                    List<KCoursePurchase> kCoursePurchaseList=kCoursePurchaseService.selectKCoursePurchaseList(kCoursePurchase);
////                    if(kCoursePurchaseList.size()>0){
////                        return AjaxResults.error("您已经报名该课程！");
////                    }
                    kCoursePurchase.setPurchaseSection(purchaseSection.intValue());
                    kCoursePurchase.setState(0);
                    // 全部
                    if(purchaseSection==0){
                        kCoursePurchase.setPrice(new BigDecimal(Integer.parseInt(kCourse.getSection().toString())).multiply(kCourse.getPrice()));
                        kCoursePurchase.setPurchaseSection(kCourse.getSection());
                    }else {
                        kCoursePurchase.setPrice(new BigDecimal(Integer.parseInt(purchaseSection.toString())).multiply(kCourse.getPrice()));
                        kCoursePurchase.setPurchaseSection(Integer.parseInt(purchaseSection.toString()));
                    }
                    String id=SnowFlakeUtil.getNextId();
                    kCoursePurchase.setOutTradeNo(id);
                    return kCoursePurchaseService.insertKCoursePurchaseForApp(kCoursePurchase,kUsers);
                default:
                    kUsers.setId(String.valueOf(userId));
//                    int rows=kUsersService.updateKUsers(kUsers);
//                    if(rows==0){
//                        return AjaxResults.error("修改用户信息失败！");
//                    }
                    //活动
                    KActivityPurchase kActivityPurchase = new KActivityPurchase();
                    kActivityPurchase.setActivityId(String.valueOf(activityId));
                    kActivityPurchase.setUserId(String.valueOf(userId));
//                    List<KActivityPurchase>  kActivityPurchaseList=kActivityPurchaseService.selectKActivityPurchaseList(kActivityPurchase);
//                    if(kActivityPurchaseList.size()>0){
//                        return AjaxResults.error("您已经报名该活动！");
//                    }
                    kActivityPurchase.setStudentName(kUsers.getNickName());
                    kActivityPurchase.setName(kUsers.getNickName());
                    kActivityPurchase.setAge(Long.valueOf(kUsers.getNickAge()));
                    kActivityPurchase.setNation(kUsers.getNickNation());
                    kActivityPurchase.setIdCard(kUsers.getNickCard());
                    kActivityPurchase.setParentName(kUsers.getHomeName());
                    kActivityPurchase.setParentPhone(kUsers.getHomePhone());
                    kActivityPurchase.setSchool(kUsers.getNickSchool());
                    kActivityPurchase.setGrade(kUsers.getNickLevel());
                    kActivityPurchase.setIsOwn(kUsers.getIsOwn());

                    KActivity kActivity=kActivityService.selectKActivityById(String.valueOf(activityId));
                    this.inserKIntegralOrder(userId,kActivity.getIntegral(),"活动报名",3,"");
                    return kActivityPurchaseService.insertKActivityPurchaseForApp(kActivityPurchase);
            }

//        }
    }


    public AjaxResults inserKIntegralOrder(Long userId,Integer score,String name,int type,String activityId){

        //增加积分 先判断有无 有修改 无新增
        KIntegralOrder kIntegralOrder =new KIntegralOrder();
        kIntegralOrder.setUserId(String.valueOf(userId));
        List<KIntegralOrder> kIntegralOrderList=kIntegralOrderService.selectKIntegralOrderList(kIntegralOrder);
        if(kIntegralOrderList.size()>0){
            kIntegralOrder.setIntegral(kIntegralOrderList.get(0).getIntegral()+score);
            kIntegralOrder.setId(kIntegralOrderList.get(0).getId());
            kIntegralOrderService.updateKIntegralOrder(kIntegralOrder);
        }else {
            kIntegralOrder.setIntegral(score);
            kIntegralOrderService.insertKIntegralOrder(kIntegralOrder);
        }

        //增加记录
        KIntegralDetailed kIntegralDetailed =new KIntegralDetailed();
        kIntegralDetailed.setUserId(String.valueOf(userId));
        kIntegralDetailed.setIntegral(score);
        kIntegralDetailed.setType(String.valueOf(type));
        kIntegralDetailed.setIntegralSource(name);
        kIntegralDetailed.setActivityId(activityId);
        kIntegralDetailedService.insertKIntegralDetailed(kIntegralDetailed);
        return  AjaxResults.success();
    }


    /*************************************************第二屏课程***********************************************/

    @ApiOperation(value = "查询课程班次列表")
    @ApiImplicitParams({
    })
    @GetMapping("/courseClassesList")
    public AjaxResult courseClassesList(KCourseClasses kCourseClasses)
    {
        List<KCourseClasses> list = kCourseClassesService.selectKCourseClassesList(kCourseClasses);
        return success(list);
    }

    @ApiOperation(value = "判断今日是否获取积分了")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "必填字段---------类型",name = "type",dataType = "int",paramType = "query"),
            @ApiImplicitParam(value = "必填字段---------当条记录的id",name = "activityId",dataType = "Long",paramType = "query")
    })
    @PostMapping("/isEarnPoints")
    public AjaxResults isEarnPoints(int type,String activityId)
    {
        Assert.notNull(type, "类型不能为空！");
        Assert.notNull(activityId, "id不能为空！");
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        //判断 今天是否浏览过
        KIntegralDetailed kIntegralDetailed =new KIntegralDetailed();
        kIntegralDetailed.setActivityId(activityId);
        kIntegralDetailed.setUserId(String.valueOf(userId));
        kIntegralDetailed.setType(String.valueOf(type));
        List<KIntegralDetailed>   kIntegralDetailedList=kIntegralDetailedService.selectKIntegralDetailedListForApp(kIntegralDetailed);
        if(kIntegralDetailedList.size()>0){
            return AjaxResults.success(1);
        }else {
            return AjaxResults.success(0);
        }
    }

    @ApiOperation(value = "浏览详情获取积分")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "必填字段---------类型",name = "type",dataType = "int",paramType = "query"),
            @ApiImplicitParam(value = "必填字段---------当条记录的id",name = "activityId",dataType = "Long",paramType = "query")
    })
    @PostMapping("/earnPoints")
    public AjaxResults earnPoints(int type,String activityId)
    {
        Assert.notNull(type, "类型不能为空！");
        Assert.notNull(activityId, "id不能为空！");
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        //判断 今天是否浏览过
        KIntegralDetailed kIntegralDetailed =new KIntegralDetailed();
        kIntegralDetailed.setActivityId(activityId);
        kIntegralDetailed.setUserId(String.valueOf(userId));
        kIntegralDetailed.setType(String.valueOf(type));
        List<KIntegralDetailed>   kIntegralDetailedList=kIntegralDetailedService.selectKIntegralDetailedListForApp(kIntegralDetailed);
        if(kIntegralDetailedList.size()>0){
            return  AjaxResults.error("今日已获取奖励！");
        }

        Integer score =0;
        String content="";
        if(type==6){ //浏览通知公告
            KNotice kNotice =kNoticeService.selectKNoticeById(activityId);
            score=kNotice.getIntegral();
            content="浏览通知公告";
        }else if(type==7){ //浏览中心概况
            KCenterOverview kCenterOverview=kCenterOverviewService.selectKCenterOverviewById(activityId);
            score=kCenterOverview.getIntegral();
            content="浏览中心概况";
        }else if(type==8){ //浏览学习之家
            KLearningHome kLearningHome=kLearningHomeService.selectKLearningHomeById(activityId);
            score=kLearningHome.getIntegral();
            content="浏览学习之家";
        }else if(type==9){ //浏览新闻
            KImportantNews kImportantNews=kImportantNewsService.selectKImportantNewsById(activityId);
            score=kImportantNews.getIntegral();
            content="浏览新闻";
        }else if(type==10){ //浏览人才招聘
            KTalentRecruitment kTalentRecruitment=kTalentRecruitmentService.selectKTalentRecruitmentById(activityId);
            score=kTalentRecruitment.getIntegral();
            content="浏览人才招聘";
        }


        return this.inserKIntegralOrder(userId,score,content,type,activityId);
    }


    @ApiOperation(value = "查询课程地点列表")
    @ApiImplicitParams({
    })
    @GetMapping("/courseLocationList")
    public AjaxResult courseLocationList(KCourseLocation kCourseLocation)
    {
        List<KCourseLocation> list = kCourseLocationService.selectKCourseLocationList(kCourseLocation);
        return success(list);
    }





    @ApiOperation(value = "查询课程班级分类列表")
    @ApiImplicitParams({
    })
    @GetMapping("/classCategoryList")
    public AjaxResult classCategoryList(KClassCategory kClassCategory)
    {
        List<KClassCategory> list = kClassCategoryService.selectKClassCategoryList(kClassCategory);
        return success(list);
    }



    @ApiOperation(value = "查询课程分类列表")
    @ApiImplicitParams({
    })
    @GetMapping("/courseTypeList")
    public AjaxResult courseTypeList(KCourseType kCourseType)
    {
        List<KCourseType> list = kCourseTypeService.selectKCourseTypeList(kCourseType);
        return success(list);
    }


    @ApiOperation(value = "查询课程信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "课程名称", paramType = "query")
    })
    @GetMapping("/courseList")
    public AjaxResults courseList(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                    @RequestParam(required = false, defaultValue = "10") Integer pageSize,KCourse kCourse)
    {
        // 查询活动是否收藏
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        KCourseCollect kCourseCollect =new KCourseCollect();
        kCourseCollect.setUserId(String.valueOf(userId));
        kCourseCollect.setIsCollect((long) 1);
        List<KCourseCollect> kCourseCollects = kCourseCollectService.selectKCourseCollectList(kCourseCollect);
        HashSet<Object> set = new HashSet<>();
        for (KCourseCollect kCourseCollect1: kCourseCollects) {
            set.add(kCourseCollect1.getCourseId());
        }

        //招生年龄 给app端显示使用
        KAgeGroup kAgeGroup =new KAgeGroup();
        List<KAgeGroup> selectKAgeGroupList = kAgeGroupService.selectKAgeGroupList(kAgeGroup);


        PageHelper.startPage(pageNum, pageSize);
        kCourse.setUserId(userId);
        kCourse.setCourseState(1);
        List<KCourse> list = kCourseService.selectKCourseListForApp(kCourse);
        List<Map<String, Object>> maps=new ArrayList<>();
        if (StringUtils.isEmpty(list))
        {
            return AjaxResults.success(new ArrayList<>());
        }else{
            for(KCourse k:list){

                //计算剩余名额
                k.setRemainingQuota2(Math.toIntExact(k.getTotalQuota() - k.getSold()));

                //字典招生年龄处理
                for (KAgeGroup kAgeGroup1:selectKAgeGroupList) {
                    if(kAgeGroup1.getId().equals(k.getAgeGroup()) ){
                        k.setAgeApp(kAgeGroup1.getName());
                        break;
                    }
                }

                //是否收藏
                k.setIsCollect((long) 0);
                if(set.contains(k.getId())){
                    k.setIsCollect((long) 1);
                }

                Map<String, Object> map = BeanUtil.beanToMap(k);
                //计算总金额
                map.put("totalPrice",(new BigDecimal(k.getSection()).multiply(k.getPrice())));
                maps.add(map);
            }
        }
        return AjaxResults.success(maps);
    }


    @ApiOperation(value = "获取课程信息详细信息")
    @ApiImplicitParams({
    })
    @GetMapping(value = "/course/{id}")
    public AjaxResult getCourseInfo(@PathVariable("id") String id)
    {
        // 查询活动是否收藏
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        KCourseCollect kCourseCollect =new KCourseCollect();
        kCourseCollect.setUserId(String.valueOf(userId));
        kCourseCollect.setIsCollect((long) 1);
        kCourseCollect.setCourseId(id);
        List<KCourseCollect> kCourseCollects = kCourseCollectService.selectKCourseCollectList(kCourseCollect);


        KCourse kCourse=kCourseService.selectKCourseByIdForApp(id);
        System.out.println("获取orderid===============================》");
        System.out.println(kCourse.getOrderId());
        kCourse.setRemainingQuota2(Math.toIntExact(kCourse.getTotalQuota() - kCourse.getSold()));
        kCourse.setActivityVenueApp(kCourseLocationService.selectKCourseLocationById(kCourse.getCourseLocation()).getName());
        kCourse.setAgeApp(kAgeGroupService.selectKAgeGroupById(kCourse.getAgeGroup()).getName());
        kCourse.setClassesApp(kCourseClassesService.selectKCourseClassesById(kCourse.getCourseClasses()).getName());
        kCourse.setClassApp(kClassCategoryService.selectKClassCategoryById(kCourse.getClassCategory()).getName());

        //

        if(kCourseCollects.size()>0){
            kCourse.setIsCollect((long) 1);
        }else {
            kCourse.setIsCollect((long) 0);
        }


        if (StringUtils.isNull(kCourse))
        {
            return success(new HashMap<>());
        }
        kCourse.setRemainingQuota2(Math.toIntExact(kCourse.getTotalQuota() - kCourse.getSold()));
        Map<String, Object> map = BeanUtil.beanToMap(kCourse);
        //计算总金额
        map.put("totalPrice",(new BigDecimal(kCourse.getSection()).multiply(kCourse.getPrice())));
        return success(map);
    }

    @ApiOperation(value = "获取课程信息报名须知信息")
    @ApiImplicitParams({
    })
    @GetMapping(value = "/notice/{id}")
    public AjaxResults getNoticeInfo(@PathVariable("id") String id)
    {
        KCourse kCourse=kCourseService.selectKCourseById(id);
        return AjaxResults.success(kCourse.getNotice());
    }





    /*************************************************第二屏中心概况***********************************************/

    @ApiOperation(value = "查询中心概况列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "分类", paramType = "query")
    })
    @GetMapping("/centerOverviewList")
    public AjaxResults centerOverviewList(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                          @RequestParam(required = false, defaultValue = "10") Integer pageSize,KCenterOverview kCenterOverview)
    {
        PageHelper.startPage(pageNum, pageSize);
        List<KCenterOverview> list = kCenterOverviewService.selectKCenterOverviewList(kCenterOverview);
        return AjaxResults.success(new PageSerializable<>(list));
    }

    @ApiOperation(value = "获取中心概况详细信息")
    @ApiImplicitParams({
    })
    @GetMapping(value = "/getCenterOverviewInfo/{id}")
    public AjaxResult getCenterOverviewInfo(@PathVariable("id") String id)
    {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        KCenterOverview kCenterOverview=kCenterOverviewService.selectKCenterOverviewById(id);
//        this.inserKIntegralOrder(userId,kCenterOverview.getIntegral(),"浏览中心概况");
        return success(kCenterOverview);
    }


    /*************************************************第二屏集体活动/比赛竞技***********************************************/


    @ApiOperation(value = "查询活动信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityType", value = "活动分类", paramType = "query")
    })
    @GetMapping("/activityList")
    public AjaxResults activityList(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                    @RequestParam(required = false, defaultValue = "10") Integer pageSize,KActivity kActivity)
    {

        // 查询活动是否收藏
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        KActivityCollect kActivityCollect =new KActivityCollect();
        kActivityCollect.setUserId(String.valueOf(userId));
        kActivityCollect.setIsCollect((long) 1);
        List<KActivityCollect> kActivityCollectList=kActivityCollectService.selectKActivityCollectList(kActivityCollect);
        HashSet<Object> set = new HashSet<>();
        for (KActivityCollect kActivityCollect1: kActivityCollectList) {
            set.add(kActivityCollect1.getActivityId());
        }

        //招生年龄 给app端显示使用
        KAgeGroup kAgeGroup =new KAgeGroup();
        List<KAgeGroup> selectKAgeGroupList = kAgeGroupService.selectKAgeGroupList(kAgeGroup);

        PageHelper.startPage(pageNum, pageSize);

            List<KActivity> list = kActivityService.selectKActivityListForApp(kActivity);
        for (KActivity kActivity1: list) {
            kActivity1.setRemainingQuota2(Math.toIntExact(kActivity1.getTotalQuota() - kActivity1.getSold()));

            //招生年龄
            for (KAgeGroup kAgeGroup1:selectKAgeGroupList) {
                if(kAgeGroup1.getId().equals(kActivity1.getAgeGroup()) ){
                    kActivity1.setAgeApp(kAgeGroup1.getName());
                    break;
                }
            }


            kActivity1.setIsCollect((long) 0);
            if(set.contains(kActivity1.getId())){
                kActivity1.setIsCollect((long) 1);
            }
        }

        return AjaxResults.success(new PageSerializable<>(list));
    }

    @ApiOperation(value = "获取活动信息详细信息")
    @ApiImplicitParams({
    })
    @GetMapping(value = "/getActivityInfo/{id}")
    public AjaxResult getActivityInfo(@PathVariable("id") String id)
    {
        KActivity kActivity =kActivityService.selectKActivityByIdForApp(id);
        // 查询活动是否收藏
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        KActivityCollect kActivityCollect =new KActivityCollect();
        kActivityCollect.setUserId(String.valueOf(userId));
        kActivityCollect.setIsCollect((long) 1);
        kActivityCollect.setActivityId(id);
        List<KActivityCollect> kActivityCollectList=kActivityCollectService.selectKActivityCollectList(kActivityCollect);
        kActivity.setAgeApp(kAgeGroupService.selectKAgeGroupById(kActivity.getAgeGroup()).getName());
        if(kActivityCollectList.size()>0){
            kActivity.setIsCollect((long) 1);
        }else {
            kActivity.setIsCollect((long) 0);
        }
        kActivity.setRemainingQuota2(Math.toIntExact(kActivity.getTotalQuota() - kActivity.getSold()));
        return success(kActivity);
    }

    @ApiOperation(value = "获取活动信息报名须知")
    @ApiImplicitParams({
    })
    @GetMapping(value = "/getActivityNotice/{id}")
    public AjaxResults getActivityNotice(@PathVariable("id") String id)
    {
        KActivity kActivity=kActivityService.selectKActivityById(id);
        return AjaxResults.success(kActivity.getNotice());
    }

    @ApiOperation(value = "课程收藏/取消")
    @GetMapping(value = "/insertKCourseCollect/{id}")
    public AjaxResults insertKCourseCollect(@PathVariable("id") String id)
    {
        //先判断 有无记录有记录则修改  无则新增
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        KCourseCollect kCourseCollect =new KCourseCollect();
        kCourseCollect.setUserId(String.valueOf(userId));
        kCourseCollect.setCourseId(id);
        List<KCourseCollect>  kCourseCollectList =kCourseCollectService.selectKCourseCollectList(kCourseCollect);
        if(kCourseCollectList.size()>0){
            if(kCourseCollectList.get(0).getIsCollect()==0){
                kCourseCollect.setIsCollect((long) 1);
                kCourseCollect.setId(kCourseCollectList.get(0).getId());
                return AjaxResults.success(kCourseCollectService.updateKCourseCollect(kCourseCollect));
            }else {
                kCourseCollect.setId(kCourseCollectList.get(0).getId());
                kCourseCollect.setIsCollect((long) 0);
                return AjaxResults.success(kCourseCollectService.updateKCourseCollect(kCourseCollect));
            }
        }else {
            kCourseCollect.setIsCollect((long) 1);
            return AjaxResults.success(kCourseCollectService.insertKCourseCollect(kCourseCollect));

        }

    }


    @ApiOperation(value = "活动收藏/取消")
    @GetMapping(value = "/insertKCourseCollectService/{id}")
    public AjaxResults insertKActivityCollectService(@PathVariable("id") String id)
    {
        //先判断 有无记录有记录则修改  无则新增
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户信息失败！");
        KActivityCollect kActivityCollect =new KActivityCollect();
        kActivityCollect.setUserId(String.valueOf(userId));
        kActivityCollect.setActivityId(id);
        List<KActivityCollect> kActivityCollectList =kActivityCollectService.selectKActivityCollectList(kActivityCollect);
        if(kActivityCollectList.size()>0){
            if(kActivityCollectList.get(0).getIsCollect()==0){
                kActivityCollect.setId(kActivityCollectList.get(0).getId());
                kActivityCollect.setIsCollect((long) 1);
                return AjaxResults.success(kActivityCollectService.updateKActivityCollect(kActivityCollect));
            }else {
                kActivityCollect.setId(kActivityCollectList.get(0).getId());
                kActivityCollect.setIsCollect((long) 0);
                return AjaxResults.success(kActivityCollectService.updateKActivityCollect(kActivityCollect));
            }
        }else {
            kActivityCollect.setIsCollect((long) 1);
            return AjaxResults.success(kActivityCollectService.insertKActivityCollect(kActivityCollect));

        }

    }

}
